<template>
    <div>
        昵称：<input type="text" id="nickname"/>
        <button @click="conectWebSocket()">连接WebSocket</button>
        <button @click="closeWebSocket()">断开连接</button>
        <hr/>
        <br/>
        消息：<input id="text" type="text"/>
        <button @click="send()">发送消息</button>
        频道号：<input id="toUser" type="text"/>
        <div id="message"></div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                websocket: null
            };
        },
        mounted() {

        },
        methods: {

            conectWebSocket() {
                const nickname = document.getElementById('nickname').value;
                if (nickname === '') {
                    alert('请输入昵称');
                    return;
                }
                let that = this
                // 判断当前浏览器是否支持WebSocket
                if ('WebSocket' in window) {
                    that.websocket = new WebSocket('ws://localhost:8090/websocket/' + nickname);
                } else {
                    alert('Not support websocket');
                }
                // 连接发生错误的回调方法
                that.websocket.onerror = function () {
                    that.setMessageInnerHTML('error');
                };
                // 连接成功建立的回调方法
                that.websocket.onopen = function (event) {
                    console.log(event)
                    that.setMessageInnerHTML('Loc MSG: 成功建立连接');
                }
                // 接收到消息的回调方法
                that.websocket.onmessage = function (event) {
                    that.setMessageInnerHTML(event.data);
                }
                // 连接关闭的回调方法
                that.websocket.onclose = function () {
                    that.setMessageInnerHTML('Loc MSG:关闭连接');
                }
                // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                window.onbeforeunload = function () {
                    that.websocket.close();
                };
            }
            ,
            // 将消息显示在网页上
            setMessageInnerHTML(innerHTML) {
                document.getElementById('message').innerHTML += innerHTML + '<br/>';
            }
            ,
            // 关闭连接
            closeWebSocket() {
                this.websocket.close();
            }
            ,
            // 发送消息
            send() {
                // 获取输入的文本信息进行发送
                const message = document.getElementById('text').value;
                const toUser = document.getElementById('toUser').value;
                const socketMsg = {msg: message, toUser: toUser};
                if (toUser === '') {
                    // 群聊.
                    socketMsg.type = 0;
                } else {
                    // 单聊.
                    socketMsg.type = 1;
                }
                this.websocket.send(JSON.stringify(socketMsg));
            }
        },
        watch: {}
    }
    ;
</script>